<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header" @click="router.back()">
        <el-icon size="20">
          <ArrowLeft />
        </el-icon>
        <span>{{ appInfo.name }}</span>
      </div>
    </template>
    <div class="desc">
      <div class="imgBox">
        <img :src="appInfo.img" />
      </div>
      <div style="flex: 1">
        <div class="appTitle">{{ appInfo.name }}</div>
        <div class="appDesc">
          {{ appInfo.blurb }}
        </div>
        <div class="info">
          <span>类型：{{ appInfo.type === '2' ? '其他' : '主应用' }}</span>
          <span>出品方：{{ appInfo.produce }}</span>
          <span>适用省份：{{ appInfo.province }}</span>
          <span>适用对象：{{ appInfo.targetObj }}</span>
        </div>
        <div class="price">{{ appInfo.price }} 元/年</div>
        <div class="priceBox">
          <span class="label">支付金额：</span>
          <span class="redPrice">￥{{ appInfo.realPrice }}</span>
          <span class="time">系统到期：{{ appInfo.expiredate }}</span>
        </div>
        <div class="btns">
          <el-button class="buy" type="primary" @click="handleBuy">{{
            buyType == 'renew' ? '续费并安装' : '购买并安装'
          }}</el-button>
          <div class="tipBox">
            <el-popover
              placement="bottom-start"
              :width="400"
              trigger="hover"
              :content="appInfo.purchaseNotes"
            >
              <template #reference>
                <span>购买须知</span>
              </template>
            </el-popover>
          </div>
        </div>
      </div>
    </div>

    <!-- tabs -->
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane label="应用简介" name="blurb">
        <p v-html="appInfo.explain" class="editor"></p>
      </el-tab-pane>
      <el-tab-pane label="使用指南" name="explain" style="padding: 0 25px">
        <p v-html="appInfo.guide" class="editor"></p>
      </el-tab-pane>
    </el-tabs>
  </el-card>

  <!-- 二维码图片 -->
  <el-dialog
    v-model="innerVisible"
    title="打开微信"
    center
    width="400"
    @close="close"
  >
    <div class="qrCode">
      <div class="codeImg">
        <QrcodeGenerator
          :text="refresh == false ? qrCodeData : 'INVALID'"
          :size="200"
          level="H"
          style="z-index: 99"
          class="overdue"
        />
        <div class="mask" v-if="refresh">
          <!-- <Refresh
            class="Refresh"
            @click="saverefresh"
            style="width: 1em; height: 1em; margin-right: 8px"
          /> -->
        </div>
      </div>
      <div>
        <span v-if="!refresh"
          >请在 {{ minutes }} 分 {{ seconds }}秒内完成支付
        </span>
        <span v-else style="font-size: 12px"
          >二维码已失效, 请点击<span @click="saverefresh" class="codeCur"
            >刷新</span
          >按钮</span
        >
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getAppInfo } from '@/api/appv2/appv2';
import { payMoney, status } from '@/api/friendshipLink/index'; //status
import QrcodeGenerator from '@/components/QrcodeGenerator/index.vue';
import { get } from 'lodash';
import { ElMessage } from 'element-plus';
import useSettingsStore from '@/store/modules/settings';
const settingsStore = useSettingsStore();
const router = useRouter();
const route = useRoute();
const buyType = ref(get(route, 'query.type', ''));
const innerVisible = ref(false);
const minutes = ref('');
const seconds = ref('');
const timeLeft = ref(0);
let pollingInterval = null; // 用于存储定时器ID
const currentTime = ref(null);
const refresh = ref(false);
//生成二维码
const qrCodeData = ref('');
const orderNum = ref('');
const totalTime = ref('');
const category = ref('');
// 应用信息
const appInfo = ref('');
const { appId } = settingsStore?.platformInfo;

const getAppInfoReq = async () => {
  const { data } = await getAppInfo({
    id: route.query.id,
    category: route.query.category,
  });
  appInfo.value = data;
};

getAppInfoReq();
// tabs
const activeName = ref('blurb');
// 倒计时分和秒的计算
minutes.value = computed(() => Math.floor(timeLeft.value / 60000)); // 60000 毫秒为 1 分钟
seconds.value = computed(() => Math.floor((timeLeft.value % 60000) / 1000)); // 1000 毫秒为 1 秒

const API = async () => {
  if (appId != route.query.id && route.query.is_must == 1) {
    category.value = '升级';
  } else if (appId != route.query.id && route.query.is_must == 0) {
    category.value = '购买';
  } else if (appId == route.query.id && route.query.is_must == 1) {
    category.value = '续费';
  }
  if (route.query.category) {
    category.value = route.query.category;
  }
  const params = ref({
    storeId: JSON.parse(localStorage.getItem('userDateInfo'))?.storeId,
    appId: appInfo.value.id,
    category: category.value,
  });
  const data = await payMoney(params.value);
  if (data.code == 20000) {
    qrCodeData.value = data.data.code_url; // 替换为你需要生成二维码的数据
    orderNum.value = data.data.out_trade_no;
    startPolling();
  }
};
// 购买
const handleBuy = async () => {
  await API();
  if (orderNum.value) {
    innerVisible.value = true;
  }
};

// 启动轮询
// 定义轮询状态的方法
const checkPaymentStatus = async () => {
  try {
    const response = await status({ order_num: orderNum.value });
    // 如果支付完成或其他条件达到，则停止轮询
    console.log('response:', response);
    if (response && response.code === 20000) {
      ElMessage({
        message: response.msg,
        type: 'success',
      });
      stopPolling();
      getAppInfoReq();
      innerVisible.value = false;
    } else {
      return;
    }
  } catch (error) {
    console.log('error:', error);
  }
};
// 启动轮询
const startPolling = () => {
  totalTime.value = Date.now() + 5 * 60 * 1000;

  pollingInterval = setInterval(() => {
    checkPaymentStatus();
    currentTime.value = Date.now();
    timeLeft.value = Math.max(0, totalTime.value - currentTime.value); // 计算剩余时间
  }, 1000); // 每1秒检查一次

  setTimeout(stopPolling, 300000); // 5分钟后停止轮询
};

// 停止轮询
const stopPolling = () => {
  clearInterval(pollingInterval);
  pollingInterval = null;
  refresh.value = true;
};
const close = () => {
  stopPolling(); // 停止轮询
  // currentTime.value = 0;
  timeLeft.value = 0; // 将剩余时间设为 0
  clearInterval(pollingInterval); // 清除计时器
  pollingInterval = null; // 将计时器变量置为空
  refresh.value = '';
};
//刷新
const saverefresh = async () => {
  API();
  refresh.value = false;
  startPolling();
};

onMounted(() => {
  console.log(route.query.id);
});
</script>

<style lang="scss" scoped>
:deep(.el-dialog__header) {
  height: 40px !important;
  max-height: 40px !important;
}
:deep(.el-dialog__body) {
  margin-top: 0cap;
}
.codeImg {
  position: relative;
  .mask {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 200px;
    height: 200px;
    background-color: rgba(255, 255, 255, 0.8);
    z-index: 100000;
    cursor: not-allowed;
    .Refresh {
      cursor: pointer;
      position: relative;
      font-size: 20px;
      top: 50%;
    }
  }
}
.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.qrCode {
  text-align: center;

  img {
    width: 200px;
    height: 200px;
  }
}

.desc {
  display: flex;
  // justify-content: space-between;
  padding: 30px;

  .imgBox {
    margin-right: 20px;
    // height: 80px;

    // img {
    //   height: 80px;
    //   width: 80px;
    // }
  }

  .appTitle {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    margin-bottom: 10px;
  }

  .appDesc {
    color: #757575;
    margin-top: 10px;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    font-size: 12px;
  }

  .info {
    color: #4a4a4a;
    margin-top: 15px;
    font-size: 12px;
    line-height: 18px;

    span:not(:first-child) {
      padding: 0 9px;
      border-left: 1px solid #e6e6e6;
    }

    span {
      padding: 0 9px;
    }
  }

  .price {
    font-size: 14px;
    color: #212121;
    line-height: 20px;
    margin-top: 15px;
    overflow: hidden;
  }

  .priceBox {
    .redPrice {
      color: #f56c6c;
      font-size: 20px;
      font-weight: 600;
    }

    .label {
      font-size: 12px;
      color: #4a4a4a;
      margin-top: 35px;
    }

    .time {
      margin-left: 10px;
      font-size: 12px;
      color: #9b9b9b;
    }
  }

  .btns {
    display: flex;
    align-items: center;
    margin-top: 35px;

    .buy {
      margin-right: 20px;
    }

    .tipBox {
      font-size: 12px;
      color: #86909c;
    }
  }
}

.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;
    display: flex;
    align-items: center;
    cursor: pointer;

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 16px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

.tip {
  max-width: 200px;
  /* 根据实际需求调整 */
  white-space: normal;
  /* 允许文本换行 */
  word-break: break-word;
  /* 处理长单词 */
  word-wrap: break-word;
  /* 确保内容能够换行 */
}
.codeCur {
  color: rgb(138, 43, 126);
  cursor: pointer;
  padding: 0 5px;
}

.mt30 {
  margin-top: 30px;
}

.demo-image__error .image-slot {
  font-size: 30px;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

:deep(.editor) {
  img {
    max-width: 100%;
  }
}
</style>
